import React, { useCallback } from "react";
import store, { RootDispatch, RootState } from "@src/store";
import { useSelector, useDispatch } from "react-redux";
import { Button, Input, Spin } from "antd";
import { UserOutlined, UnlockOutlined } from "@ant-design/icons";
import "./style.css";

const FuncReduxExample = function FuncReduxExample() {
  const isLoading = useSelector<RootState, RootState["loading.global"]>((state) => state.loading.global);
  const isLogin = useSelector<RootState, RootState["global.isLogin"]>((state) => state.global.isLogin);
  /**
   * 使用react-redux hook
   * 在将一个使用了 dispatch 函数的回调函数传递给子组件时，
   * 建议使用 useCallback 函数将回调函数记忆化，防止因为回调函数引用的变化导致不必要的渲染。
   */
  const dispatch = useDispatch<RootDispatch>();
  const logout = useCallback(() => dispatch({ type: "global/fetchLogout", payload: 123 }), [dispatch]);
  /**
   * 直接使用rematch的实例
   */
  const login = () => {
    store.dispatch.global.fetchLogin(123);
  };
  return (
    <div className="funcReduxExample-page">
      <Spin tip="正在登录..." spinning={isLoading}>
        <div className="li">
          <Input size="large" placeholder="用户名" prefix={<UserOutlined />} />
        </div>
        <div className="li">
          <Input.Password size="large" placeholder="密码" prefix={<UnlockOutlined />} />
        </div>
        <div className="li">
          <Button type={isLogin ? "default" : "primary"} disabled={isLogin} block onClick={login}>
            Login
          </Button>
        </div>
        <div className="li">
          <Button type={!isLogin ? "default" : "primary"} disabled={!isLogin} block onClick={logout}>
            Logout
          </Button>
        </div>
      </Spin>
    </div>
  );
};
export default FuncReduxExample;
